﻿var CloudTreeList = [];
var CloudTreMap = new Map();
function RenderTree() {
    //获取所有cloudtree标签的对象
    var cloudTreeList = $("cloud-tree");
    for (var i = 0; i < cloudTreeList.length; i++) {
        var cloudTree = cloudTreeList[i];
        var id = "cloud" + $(cloudTree).attr("id");
        var readonly = "cloud" + $(cloudTree).attr("readonly");
        var url = $(cloudTree).attr("url");
        var selectvalue = $(cloudTree).attr("selectvalue");
        //select/selectgroup/selectou/selectmodule/selectcode/selectproject
        var controltype = $(cloudTree).attr("control-type");
        //single/multi/
        var selecttype = $(cloudTree).attr("select-type");
        //自定义快速数据源时的参数
        //分组树
        var grouptag = $(cloudTree).attr("grouptag");
        //代码项树
        var mainguid = $(cloudTree).attr("mainguid");
        var nodeclick = $(cloudTree).attr("nodeclick");
        var codeid = id + "_code";
        var treecontainerid = id + "_ztree_cotainer"
        var treecontaineropid = id + "_treeop_container"
        var treeid = id + "_ztree"
        var text = "";
        text += " <input id=" + id + "  class=\"cloudtree-select\"   readonly style='" + $(cloudTree).attr('style') + "'  > ";
        //text += "    <!-- 模拟select点击框 以及option的text值显示-->";
        //text += "    <i class=\"cloudtree-drop\" ></i>";
        //text += "    <!-- 模拟select右侧倒三角 -->";
        //text += "    <input id=" + codeid + " type=\"hidden\"  />";
        text += "    <!-- zTree树状图 相对定位在其下方 -->";
        text += "    <div id=" + treecontainerid + "  class=\"cloudtree-container\">";
        if (!readonly) {
            text += "       <div id='" + treecontaineropid + "' class='cloudtree-select-op' style='display:none'>";
            text += "           <input id='" + treecontaineropid + "_searchinput'  type='text' class='form-control tree-search-input' placeholder='请输入搜索内容' style='height:25px'>"
            //text += "          <button id='" + treecontaineropid+"_search' class='treeopbtn' optype='search' type='button' <span class='searchtext'>搜索</span></button>"
            text += "           <button  id='" + treecontaineropid + "_clear' class='treeopbtn' optype='clear' type='button' <span class='searchtext'>清除</span></button>"
            text += "           <button  id='" + treecontaineropid + "_close' class='treeopbtn' optype='close' type='button' <span class='searchtext'>关闭</span></button>"
            text += "       </div>"
        }
        text += "        <ul class=\"ztree\" id=" + treeid + "></ul>";
        text += "    </div>  ";
        cloudTree.innerHTML = text;
        var CloudTreeObj = { "id": id, "treeid": treeid, "controltype": controltype, "selecttype": selecttype, "grouptag": grouptag, "mainguid": mainguid };
        if (selectvalue && selectvalue != "") {
            CloudTreeObj.selectvalue = selectvalue;
        }
        CloudTreeList.push(CloudTreeObj);
        var CloudTreeDataObj = { "Nodes": [], "HideNodes": [] };
        CloudTreMap.set(id, CloudTreeDataObj);
        InitTree(id, url, nodeclick);
        $("#" + treecontainerid).css("width", $("#" + id).outerWidth())

    }
    BindTreeClick();
}

function BindTreeClick() {
    $(".cloudtree-select").click(function () {
        var readonly = $("#" + $(this).attr("id").replace("cloud","")).attr("readonly");
        if (!readonly) {
            ShowTree($(this).attr("id"));
        }
    });
    $(".treeopbtn").click(function () {
        var opbtnid = $(this).attr("id");
        var optype = $(this).attr("optype");
        var controlid = opbtnid.split('_')[0];
        var treeid = controlid + "_ztree"
        var treeObj = $.fn.zTree.getZTreeObj(treeid);
        if (optype == 'search') {

        } else if (optype == 'clear') {
            treeObj.checkAllNodes(false);
            treeObj.cancelSelectedNode();
            $(treeObj).attr("selectvalue", "")
            $("#" + controlid).val("");
        } else if (optype == 'close') {
            HideTree(controlid);
        }
    });
    $(".tree-search-input").each(function () {
        $(this).on("input", function () {
            var id = $(this).attr("id");
            var controlid = id.split('_')[0];
            var treeid = controlid + "_ztree"
            var treeObj = $.fn.zTree.getZTreeObj(treeid);
            var ztreeInput = $(this).val();
            var readonly = $("#" + controlid).attr("readonly");
            if (!readonly) {
                treeObj.showNodes(CloudTreMap.get(controlid).HideNodes);
                var hiddenNodes = [];
                function filterFunc(node) {
                    var keyword = ztreeInput;
                    //如果当前结点，或者其父结点可以找到，或者当前结点的子结点可以找到，则该结点不隐藏
                    if (SearchParent(keyword, node) || SearchChildren(keyword, node.children)) {
                        return false;
                    }
                    return true;
                };
                //获取不符合条件的叶子结点
                hiddenNodes = treeObj.getNodesByFilter(filterFunc);
                CloudTreMap.get(controlid).HideNodes = hiddenNodes;
                //隐藏不符合条件的叶子结点
                treeObj.hideNodes(hiddenNodes);
            }
        })
    })
}



function InitTree(ID, TreeDataUrl, TreeOnClick) {
    var TreeID = ID + "_ztree"
    var TreeContainerID = ID + "_ztree_cotainer"
    var CloudTreeObj = GetTreeObj(ID)
    var setting = {
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式 
                idKey: "id",   //节点数据中保存唯一标识的属性名称
                pIdKey: "pid",    //节点数据中保存其父节点唯一标识的属性名称 
                rootPId: -1,  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                name: "name"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            },
        },
        check: {

        },
        callback: {

        }
    };
    if (CloudTreeObj.selecttype == "single") {
        setting.check.enable = true;
        setting.check.chkStyle = "radio";
        setting.check.radioType = "all";
    } else {
        setting.check.enable = true;
        setting.check.chkStyle = "checkbox";
        setting.check.chkboxType = { "Y": "ps", "N": "ps" }
    }
    if (TreeOnClick) {
        setting.callback.onClick = TreeOnClick
    } else {
        if (CloudTreeObj.selecttype == "single") {
            setting.callback.onClick = function (event, treeId, treeNode, clickFlag) {
                var treeObj = $.fn.zTree.getZTreeObj(TreeID);
                var nodes = treeObj.getSelectedNodes();
                for (var i = 0, l = nodes.length; i < l; i++) {
                    if (nodes[i].id == treeNode.id) {
                        treeObj.checkNode(nodes[i], true, true);
                    }
                }
                CloudTreeObj.selectvalue = treeNode.id;
                CloudTreeObj.selectname = treeNode.name;
                $(treeObj).attr("selectvalue", treeNode.id)
                $("#" + ID).val(treeNode.name);
                HideTree(ID)
            }
            setting.callback.onCheck = function (event, treeId, treeNode, clickFlag) {
                var treeObj = $.fn.zTree.getZTreeObj(TreeID);
                CloudTreeObj.selectvalue = treeNode.id;
                CloudTreeObj.selectname = treeNode.name;
                $(treeObj).attr("selectvalue", treeNode.id)
                $("#" + ID).val(treeNode.name);
                HideTree(ID)
            }
        } else {
            //多选
            setting.callback.onCheck = function (event, treeId, treeNode, clickFlag) {
                var treeObj = $.fn.zTree.getZTreeObj(TreeID);
                var selectNodeList = treeObj.getCheckedNodes();
                var treeIDList = "";
                var treeNameList = "";
                $(selectNodeList).each(function () {
                    //顶级节点或不纳入统计的节点不计算选项
                    if (this.id != "Top" && this.inSelectResult) {
                        treeIDList += this.id + ";";
                        treeNameList += this.name + ";";
                    }
                })
                CloudTreeObj.selectvalue = treeIDList;
                CloudTreeObj.selectname = treeNameList;
                $(treeObj).attr("selectvalue", treeIDList)
                $("#" + ID).val(treeNameList);
            }
        }

    }
    if (CloudTreeObj.controltype == "selectgroup") {
        CloudPost({ "GroupTag": CloudTreeObj.grouptag }, GetRootPath() + "frame/base/group/grouptree", function (res) {
            if (res.code == 0) {
                var TreeNode = res.data
                CloudTreMap.get(ID).Nodes = TreeNode;
                zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, TreeNode);
                CloudTreeObj.zTreeObj = zTreeObj;
                if (CloudTreeObj.selectvalue && CloudTreeObj.selectvalue != "") {
                    SetNodeChecked(ID);
                }
            }
        })
    }
    else if (CloudTreeObj.controltype == "selectou") {
        CloudPost({}, GetRootPath() + "frame/org/ou/tree", function (res) {
            if (res.code == 0) {
                var TreeNode = res.data;
                CloudTreMap.get(ID).Nodes = TreeNode;
                zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, TreeNode);
                CloudTreeObj.zTreeObj = zTreeObj;
                if (CloudTreeObj.selectvalue && CloudTreeObj.selectvalue != "") {
                    SetNodeChecked(ID);
                }
            }
        })
    }
    else if (CloudTreeObj.controltype == "selectuser") {
        CloudPost({}, GetRootPath() + "frame/org/user/tree", function (res) {
            if (res.code == 0) {
                var TreeNode = res.data;
                if (CloudTreeObj.selecttype == "single") {
                    SyncNodeDataNoCheck(TreeNode)
                }
                CloudTreMap.get(ID).Nodes = TreeNode;
                zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, TreeNode);
                CloudTreeObj.zTreeObj = zTreeObj;
                if (CloudTreeObj.selectvalue && CloudTreeObj.selectvalue != "") {
                    SetNodeChecked(ID);
                }
            }
        })
    }
    else if (CloudTreeObj.controltype == "selectmodule") {
        CloudPost({}, GetRootPath() + "frame/org/module/tree", function (res) {
            if (res.code == 0) {
                var TreeNode = res.data;
                CloudTreMap.get(ID).Nodes = TreeNode;
                zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, TreeNode);
                CloudTreeObj.zTreeObj = zTreeObj;
                if (CloudTreeObj.selectvalue && CloudTreeObj.selectvalue != "") {
                    SetNodeChecked(ID);
                }
            }
        })
    }
    else if (CloudTreeObj.controltype == "selectcode") {
        CloudPost({ "MainGuid": CloudTreeObj.mainguid }, GetRootPath() + "frame/dmp/codeitem/tree", function (res) {
            if (res.code == 0) {
                var TreeNode = res.data;
                CloudTreMap.get(ID).Nodes = TreeNode;
                zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, TreeNode);
                CloudTreeObj.zTreeObj = zTreeObj;
                if (CloudTreeObj.selectvalue && CloudTreeObj.selectvalue != "") {
                    SetNodeChecked(ID);
                }
            }
        })
    } else if (CloudTreeObj.controltype == "selectproject") {
        CloudPost({ "MainGuid": CloudTreeObj.mainguid }, GetRootPath() + "frame/dmp/project/tree", function (res) {
            if (res.code == 0) {
                var TreeNode = res.data;
                CloudTreMap.get(ID).Nodes = TreeNode;
                zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, TreeNode);
                CloudTreeObj.zTreeObj = zTreeObj;
                if (CloudTreeObj.selectvalue && CloudTreeObj.selectvalue != "") {
                    SetNodeChecked(ID);
                }
            }
        })
    }
    else {
        CloudPost({}, TreeDataUrl, function (res) {
            if (res.code == 0) {
                var TreeNode = res.data;
                CloudTreMap.get(ID).Nodes = TreeNode;
                zTreeObj = $.fn.zTree.init($("#" + TreeID), setting, TreeNode);
                CloudTreeObj.zTreeObj = zTreeObj;
                if (CloudTreeObj.selectvalue && CloudTreeObj.selectvalue != "") {
                    SetNodeChecked(ID);
                }
            }
        })
    }

}

function ShowTree(ID) {
    var TreeContainerID = ID + "_ztree_cotainer"
    var TreeContainerOPID = ID + "_treeop_container"
    $('#' + TreeContainerID).css('display', 'block');
    $('#' + TreeContainerOPID).css('display', 'flex');
    $("body").bind("mousedown", function (event) {
        if (event.target.id.indexOf(ID) == -1 && event.target.id.indexOf(TreeContainerID) == -1) {
            if (event.target.id != 'selectDevType') {
                HideTree(ID);
            }
        }
    });

}

function HideTree(ID) {
    var TreeContainerID = ID + "_ztree_cotainer"
    var TreeContainerOPID = ID + "_treeop_container"
    $("#" + TreeContainerID).css('display', 'none');
    $("#" + TreeContainerOPID).css('display', 'none');
    $("body").unbind("mousedown");
    return false;
}

function GetTreeObj(ID) {
    var CloudTreeObj;
    for (var i = 0; i < CloudTreeList.length; i++) {
        if (CloudTreeList[i].id == ID) {
            CloudTreeObj = CloudTreeList[i];
        }
    }
    return CloudTreeObj;
}

function GetTreeSelectValue(ID) {
    return GetTreeObj("cloud" + ID).selectvalue;
}

function SetNodeChecked(ID) {
    var CloudTreeObj = GetTreeObj(ID);
    var TreeID = ID + "_ztree"
    var treeObj = $.fn.zTree.getZTreeObj(TreeID);
    var nodes = treeObj.getNodesByFilter(function (node) {
        return CloudTreeObj.selectvalue.indexOf(node.id) > -1;
    });
    for (var i = 0, l = nodes.length; i < l; i++) {
        $("#" + ID).val(nodes[i].name)
        treeObj.checkNode(nodes[i], true, true);
    }
}

/**
 * 查找子结点，如果找到，返回true，否则返回false-----ztree查询时使用
 */
function SearchChildren(keyword, children) {
    if (children == null || children.length == 0) {
        return false;
    }
    for (var i = 0; i < children.length; i++) {
        var node = children[i];
        if (node.name.indexOf(keyword) != -1) {
            return true;
        }
        //递归查找子结点
        var result = SearchChildren(keyword, node.children);
        if (result) {
            return true;
        }
    }
    return false;
}

/**
 * 查找当前结点和父结点，如果找到，返回ture，否则返回false
 */
function SearchParent(keyword, node) {
    if (node == null) {
        return false;
    }
    if (node.name.indexOf(keyword) != -1) {
        return true;
    }
    //递归查找父结点
    return SearchParent(keyword, node.getParentNode());
}

function SyncNodeDataNoCheck(TreeNode) {
    $(TreeNode).each(function () {
        this.nocheck = !TreeNode.inSelectResult;
        if (this.children) {
            $(this.children).each(function () {
                SyncNodeDataNoCheck(this);
            })
        }
    })
  
}
